package com.android.lightcontroler;

import com.Charlie.Utils.LightController;
import com.Charlie.Utils.LightController.ConnectStateCallback;

import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.GridView;
import android.widget.ImageButton;
import android.widget.RadioGroup;
import android.widget.RadioGroup.OnCheckedChangeListener;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
import android.widget.TextView;

public class LightControlActivity extends Activity implements OnClickListener,
		ConnectStateCallback {

	private static String IP = "192.168.1.100";
	private static int Port = 50000;

	private GridView mGridView;
	private ImageButton mListBtn;
	private ImageButton mMoreFunctionBtn;
	private TextView mTitleView;
	private RadioGroup mOnOffBtnGroup;
	private SeekBar mSeekBar;
	private String ids[];
	private String addrs[];
	private Button mWhiteBtn, mRedBtn, mGreenBtn, mBlueBtn;

	private int[] colorArray = { 0xFFFF0000, 0xFFFF3300, 0xFFFF6600,
			0xFFFF9900, 0xFFFFCC00, 0xFFFFFF00, 0xFFCCFF00, 0xFF99FF00,
			0xFF66FF00, 0xFF33FF00, 0xFF00FF99, 0xFF00FFFF, 0xFF00CCFF,
			0xFF0099FF, 0xFF0033FF, 0xFF0000FF, 0xFF3300FF, 0xFF6600FF,
			0xFF9900FF, 0xFFFF00FF, 0xFFFF00CC, 0xFFFF0099, 0xFFFF0099,
			0xFFFF0033, 0xFFCC3333, 0xFFC4723C, 0xFFC4A93C, 0xFFC4C43C,
			0xFF8CBB44, 0xFF55AA66, 0xFF4DB38A, 0xFF5599AA, 0xFF5566AA,
			0xFF4D4DB3, 0xFF7755AA, 0xFF9955AA, 0xFFAA5577, 0xFFB34D61,
			0xFF996699, 0xFFC4723C, 0xFFC4A93C, 0xFFC4C43C };

	@Override
	protected void onCreate(Bundle savedInstanceState) {

		super.onCreate(savedInstanceState);
		setContentView(R.layout.light_control_page);
		initView();
		initData();
		LightController.shareInstance().setStateCallback(this);
		LightController.shareInstance().connect(IP, Port);
	}

	/**
	 * 初始化本地数据
	 * 
	 * 2014-4-22
	 */
	protected void initData() {
		SharedPreferences sp = this.getSharedPreferences("light_data",
				MODE_PRIVATE);
		String strIds = sp.getString("ids", "");
		String strAddrs = sp.getString("addrs", "");
		String strTitle = sp.getString("title", "");

		if (!"".equals(strIds)) {
			ids = strIds.split("@");
		}

		if (!"".equals(strAddrs)) {
			addrs = strAddrs.split("@");
		}

		if (strTitle == null || "".equals(strTitle)) {
			mTitleView.setText("No lights");
		} else {
			mTitleView.setText(strTitle);
		}
	}

	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();

		/* 如果什么都没选，就存空值 4.22 廖朝瑞 */
		StringBuffer strIds = new StringBuffer("");
		StringBuffer strAddrs = new StringBuffer("");

		if (ids != null) {
			for (int i = 0; i < ids.length; i++) {
				strIds.append(ids[i]);
				strAddrs.append(addrs[i]);
				if (i < ids.length - 1) {
					strIds.append("@");
					strAddrs.append("@");
				}
			}
		}

		SharedPreferences sp = this.getSharedPreferences("light_data",
				MODE_PRIVATE);
		SharedPreferences.Editor editor = sp.edit();
		editor.putString("ids", strIds.toString());
		editor.putString("addrs", strAddrs.toString());
		editor.putString("title", mTitleView.getText().toString());
		editor.commit();
	}

	protected void initView() {
		mOnOffBtnGroup = (RadioGroup) findViewById(R.id.on_off_radiogroup);
		mTitleView = (TextView) findViewById(R.id.title_name);
		mListBtn = (ImageButton) findViewById(R.id.list_btn);
		mListBtn.setOnClickListener(this);
		mGridView = (GridView) findViewById(R.id.color_gridview);
		mGridView.setAdapter(new GridViewAdapter());
		mSeekBar = (SeekBar) findViewById(R.id.ld_seekBar);
		mMoreFunctionBtn = (ImageButton) findViewById(R.id.more_btn);
		mMoreFunctionBtn.setOnClickListener(this);

		mWhiteBtn = (Button) findViewById(R.id.white_btn);
		mRedBtn = (Button) findViewById(R.id.red_btn);
		mGreenBtn = (Button) findViewById(R.id.green_btn);
		mBlueBtn = (Button) findViewById(R.id.blue_btn);
		mWhiteBtn.setOnClickListener(this);
		mRedBtn.setOnClickListener(this);
		mGreenBtn.setOnClickListener(this);
		mBlueBtn.setOnClickListener(this);

		mOnOffBtnGroup
				.setOnCheckedChangeListener(new OnCheckedChangeListener() {

					@Override
					public void onCheckedChanged(RadioGroup group, int checkedId) {
						// TODO Auto-generated method stub
						switch (checkedId) {
						case R.id.on_btn: // 开灯
							if (LightController.shareInstance().isConnected()
									&& addrs != null) {
								for (int i = 0, length = addrs.length; i < length; i++) {
									if (addrs[i] != null
											&& !"".equals(addrs[i])) {
										LightController.shareInstance()
												.openTheLight(addrs[i]);
									}
								}
							}
							break;
						case R.id.off_btn: // 关灯
							if (LightController.shareInstance().isConnected()
									&& addrs != null) {
								for (int i = 0, length = addrs.length; i < length; i++) {
									if (addrs[i] != null
											&& !"".equals(addrs[i])) {
										LightController.shareInstance()
												.closeTheLight(addrs[i]);
									}
								}
							}
							break;
						default:
							break;
						}
						if (checkedId != -1) {
							mOnOffBtnGroup.clearCheck();
						}
					}
				});

		// 设置灯颜色
		mGridView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				// TODO Auto-generated method stub
				if (LightController.shareInstance().isConnected()
						&& addrs != null) {
					for (int i = 0, length = addrs.length; i < length; i++) {
						if (addrs[i] != null && !"".equals(addrs[i])) {
							LightController.shareInstance().setLightColor(
									colorArray[arg2], addrs[i]);
						}
					}
				}
			}
		});

		mSeekBar.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {

			@Override
			public void onStopTrackingTouch(SeekBar seekBar) {
				// TODO Auto-generated method stub
				if (LightController.shareInstance().isConnected()
						&& addrs != null) {
					for (int i = 0, length = addrs.length; i < length; i++) {
						if (addrs[i] != null && !"".equals(addrs[i])) {
							LightController.shareInstance().setLightBrightness(
									mSeekBar.getProgress(), addrs[i]);
						}
					}
				}
			}

			@Override
			public void onStartTrackingTouch(SeekBar seekBar) {
				// TODO Auto-generated method stub

			}

			@Override
			public void onProgressChanged(SeekBar seekBar, int progress,
					boolean fromUser) {
				// TODO Auto-generated method stub
			}
		});
	}

	class GridViewAdapter extends BaseAdapter {

		GridView.LayoutParams params;

		public GridViewAdapter() {
			int itemWidth = dip2px(LightControlActivity.this, 40);
			params = new GridView.LayoutParams(itemWidth, itemWidth);
		}

		@Override
		public int getCount() {
			// TODO Auto-generated method stub
			return colorArray.length;
		}

		@Override
		public Object getItem(int position) {
			// TODO Auto-generated method stub
			return colorArray[position];
		}

		@Override
		public long getItemId(int position) {
			// TODO Auto-generated method stub
			return position;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			// TODO Auto-generated method stub
			if (convertView == null) {
				TextView tv = new TextView(LightControlActivity.this);
				tv.setLayoutParams(params);
				convertView = tv;
			}
			convertView.setBackgroundColor(colorArray[position]);
			return convertView;
		}

	}

	public static int dip2px(Context context, float dpValue) {
		final float scale = context.getResources().getDisplayMetrics().density;
		return (int) (dpValue * scale + 0.5f);
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.list_btn:
			Intent listIntent = new Intent(this, LightListActivity.class);
			if (ids != null) {
				listIntent.putExtra("ids", ids);
			}
			startActivityForResult(listIntent, 1);
			break;
		case R.id.more_btn:
			Intent moreFunctionIntent = new Intent(this,
					MoreFunctionActivity.class);
			if (addrs != null) {
				moreFunctionIntent.putExtra("addrs", addrs);
				moreFunctionIntent.putExtra("brightness",
						mSeekBar.getProgress());
			}
			startActivity(moreFunctionIntent);
			break;
		case R.id.white_btn:
			if (LightController.shareInstance().isConnected() && addrs != null) {
				for (int i = 0, length = addrs.length; i < length; i++) {
					if (addrs[i] != null && !"".equals(addrs[i])) {
						LightController.shareInstance().setLightOnlyWhite(
								mSeekBar.getProgress(), addrs[i]);
					}
				}
			}
			break;
		case R.id.red_btn:
			if (LightController.shareInstance().isConnected() && addrs != null) {
				for (int i = 0, length = addrs.length; i < length; i++) {
					if (addrs[i] != null && !"".equals(addrs[i])) {
						LightController.shareInstance().setLightOnlyRed(
								addrs[i]);
					}
				}
			}
			break;
		case R.id.green_btn:
			if (LightController.shareInstance().isConnected() && addrs != null) {
				for (int i = 0, length = addrs.length; i < length; i++) {
					if (addrs[i] != null && !"".equals(addrs[i])) {
						LightController.shareInstance().setLightOnlyGreen(
								addrs[i]);
					}
				}
			}
			break;
		case R.id.blue_btn:
			if (LightController.shareInstance().isConnected() && addrs != null) {
				for (int i = 0, length = addrs.length; i < length; i++) {
					if (addrs[i] != null && !"".equals(addrs[i])) {
						LightController.shareInstance().setLightOnlyBlue(
								addrs[i]);
					}
				}
			}
			break;
		default:
			break;
		}
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);
		if (requestCode == 1 && resultCode == Activity.RESULT_OK) {
			ids = data.getStringArrayExtra("ids");
			addrs = data.getStringArrayExtra("addr");

			/* 有选中就读取，选中信息，没有就显示 No lights 4.22 廖朝瑞 */
			if (ids != null) {
				if (ids.length == 1) {
					mTitleView.setText(data.getStringExtra("name"));
				} else if (ids.length > 1) {
					mTitleView.setText("Multiple lights");
				}
			} else {
				mTitleView.setText("No lights");
			}
		}
	}

	@Override
	public void didConnectToHost(String host, int port) {
		// TODO Auto-generated method stub

	}

	@Override
	public void didDisconnectToHost(String host, int port) {
		// TODO Auto-generated method stub
		new Thread(new Runnable() {

			@Override
			public void run() {
				// TODO Auto-generated method stub
				try {
					Thread.sleep(2000);
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				LightController.shareInstance().connect(IP, Port);
			}
		});
	}
}
